<script setup lang="tsx">
import { ref, inject, computed } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { getList, getInfo } from '@/api/task/financial';
import { getDictionaries } from '@/api/member/deposit';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    title: '订单号',
    colKey: 'orderNumber',
  },
  {
    title: '流水号',
    colKey: 'tradeNumber',
  },
  {
    title: '代理线',
    colKey: 'abc',
  },
  {
    title: '账号',
    colKey: 'username',
  },
  {
    title: '交易类型',
    colKey: 'type',
  },
  {
    title: '交易金额',
    colKey: 'tradeAmount',
  },
  {
    title: '交易前余额',
    colKey: 'tradeBeforeBalance',
  },
  {
    title: '交易后余额',
    colKey: 'accountBalance',
  },
  {
    title: '交易状态',
    colKey: 'state',
    cell: (h: any, { row }: { row: any }) => {
      return (
        <Space>
          {row.state == '1' && (
            <t-tag theme="primary" variant="light">
              成功
            </t-tag>
          )}
          {row.state == '0' && (
            <t-tag theme="danger" variant="light">
              失败
            </t-tag>
          )}
        </Space>
      );
    },
  },
  {
    title: '说明备注',
    colKey: 'remarks',
  },
  {
    title: '交易时间',
    colKey: 'tradeTime',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const footData = computed(() => {
  const totalMoney = data.value.reduce((sum, item) => sum + (item.tradeAmount || 0), 0);

  return [
    {
      orderNumber: '合计',
      // 格式化显示
      tradeAmount: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney),
    },
  ];
});

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  orderNumber: string | null;
  tradeNumber: string | null;
  username: string | null;
  type: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  orderNumber: undefined,
  tradeNumber: undefined,
  username: undefined,
  type: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.orderNumber} placeholder="订单号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.tradeNumber} placeholder="流水号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.username} placeholder="账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.type} placeholder="交易类型">
        {typeList.value?.map((item) => <t-option key={item.dictValue} label={item.dictLabel} value={item.dictValue} />)}
      </t-select>
      <t-date-range-picker v-model={dateRange.value} placeholder="交易时间" />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="finId"
      onUnGetList={unGetList}
      footData={footData.value}
    >
      {{
        tradeAmount: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.tradeAmount,
            )}
          </div>
        ),
        tradeBeforeBalance: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.tradeBeforeBalance,
            )}
          </div>
        ),
        accountBalance: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.accountBalance,
            )}
          </div>
        ),
        type: (slotProps: any) => <div>{getName('dictValue', slotProps.row.type, typeList.value, 'dictLabel')}</div>,
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              详情
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,

      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

const typeList = ref([]);
// 获取类型
const unGetDictionaries = () => {
  getDictionaries({}).then((res) => {
    typeList.value = res.data;
    unGetList();
  });
};
unGetDictionaries();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  dateRange.value = [];
  unGetList();
};

// 详情
const formObj = new formGroup();
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.finId);
    formObj.show(
      '流水详情',
      {
        ...res.data,
      },
      '流水详情',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>('流水详情', '流水详情', {}, undefined, {});

const getName = (lid: any, id: any, list: any, name: any) => {
  if (!id) return '';
  return list.find((item: { [x: string]: any }) => item[lid] == id)[name];
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加等级对话框 -->
        <template v-if="item == '流水详情'">
          <t-form-item label="订单号" name="orderNumber">
            <div>{{ formData.orderNumber }}</div>
          </t-form-item>
          <t-form-item label="流水号" name="tradeNumber">
            <div>{{ formData.tradeNumber }}</div>
          </t-form-item>
          <t-form-item label="用户" name="username">
            <div>{{ formData.username }}</div>
          </t-form-item>
          <t-form-item label="目标" name="abc">
            <div>{{ formData.abc }}</div>
          </t-form-item>
          <t-form-item label="交易类型" name="type">
            <div>{{ getName('dictValue', formData.type, typeList, 'dictLabel') }}</div>
          </t-form-item>
          <t-form-item label="交易金额" name="tradeAmount">
            <div>
              {{
                new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
                  formData.tradeAmount,
                )
              }}
            </div>
          </t-form-item>
          <t-form-item label="交易前余额" name="tradeBeforeBalance">
            <div>
              {{
                new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
                  formData.tradeBeforeBalance,
                )
              }}
            </div>
          </t-form-item>
          <t-form-item label="交易后余额" name="accountBalance">
            <div>
              {{
                new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
                  formData.accountBalance,
                )
              }}
            </div>
          </t-form-item>
          <t-form-item label="说明备注" name="remarks">
            <div>{{ formData.remarks }}</div>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
  </div>
</template>
